# -*- coding = utf-8 -*-
# @Time : 2021/7/21 19:03
# @Author : Z_C_Lee
# @File : model.py
# @Software : PyCharm

import paddle
import paddle.nn.functional as F
import cv2
import numpy as np
import pymysql
import sys

def get_data(a):
    # 与 mysql 建立连接
    conn = pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='crop_2',charset='utf8')

    # sql 语句定义为一个字符串
    sql_search = 'select p.pic from temporary_pic p where id=' + a + ';'
    cursor = conn.cursor()
    cursor.execute(sql_search)
    fout = open("D:\\My_Code\\springboot+vue\\crop2.0\\springboot\\src\\main\\resources\\pyFile\\pics\\" + a + '.jpg', 'wb')
    fout.write(cursor.fetchone()[0])
    cursor.close()
    conn.close()

def identify(a):
    img1 = cv2.imread("D:\\My_Code\\springboot+vue\\crop2.0\\springboot\\src\\main\\resources\\pyFile\\pics\\" + a + ".jpg")
    img2 = cv2.resize(img1, (64, 64), interpolation=cv2.INTER_AREA) / 255

    r = []
    g = []
    b = []

    r.append(img2[:, :, 0])
    g.append(img2[:, :, 1])
    b.append(img2[:, :, 2])

    one_data = np.concatenate((r, g, b), axis=0)
    one_data = np.expand_dims(one_data, axis=0)
    one_data = paddle.to_tensor(one_data, dtype="float32")

    model = MyNet(num_classes=61)

    load_file = paddle.load("D:\\My_Code\\springboot+vue\\crop2.0\\springboot\\src\\main\\resources\\pyFile\\source\\model.pdparams")
    model.set_state_dict(load_file)
    logits = model(one_data)
    a = F.softmax(logits, axis=-1)
    label = np.argmax(a.numpy())
    print(label)

# 网络结构
class MyNet(paddle.nn.Layer):
    def __init__(self, num_classes=1):
        super(MyNet, self).__init__()

        self.conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=32, kernel_size=(3, 3))
        self.pool1 = paddle.nn.MaxPool2D(kernel_size=2, stride=2)

        self.conv2 = paddle.nn.Conv2D(in_channels=32, out_channels=64, kernel_size=(3, 3))
        self.pool2 = paddle.nn.MaxPool2D(kernel_size=2, stride=2)

        self.conv3 = paddle.nn.Conv2D(in_channels=64, out_channels=64, kernel_size=(3, 3))

        self.flatten = paddle.nn.Flatten()

        self.linear1 = paddle.nn.Linear(in_features=64*12*12, out_features=128)
        self.linear2 = paddle.nn.Linear(in_features=128, out_features=num_classes)

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.pool1(x)

        x = self.conv2(x)
        x = F.relu(x)
        x = self.pool2(x)

        x = self.conv3(x)
        x = F.relu(x)

        x = self.flatten(x)
        x = self.linear1(x)
        x = F.relu(x)
        x = self.linear2(x)
        return x



if __name__ == '__main__':
    for i in range(1, len(sys.argv)):
        strs = sys.argv[i]
        get_data(strs)
        identify(strs)

